package cn.bone.zk.zk02;

import com.alibaba.fastjson.JSON;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ZkClient {

    private String name;
    private ZooKeeper zkClient;
    private final List<String> children = new ArrayList<>();

    public ZkClient(String name){
        this.name = name;
    }

    public void init(){
        String connectString = "192.168.1.5:2001,192.168.1.5:2002,192.168.1.5:2003";
        int sessionTimeout = 2000;
        try {
            zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    try {
                        List<String> childList = zkClient.getChildren("/servers", true);
                        children.clear();
                        children.addAll(childList);
                        System.out.println(name + " : " +JSON.toJSONString(children));
                        for(String child : children){
                            byte[] data = zkClient.getData("/servers" + child, false, null);
                            System.out.println(new String(data));
                        }
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
